import numpy as np
import math
import matplotlib.pyplot as plt

UFL = pow(2, -1)
OFL = pow(2, 1) * (2 - pow(2, 1-3))

print('UFL = ', UFL)
print('OFL = ', OFL)

FPN_numbers = []
e = -1
m = [1, 0, 0]

while e < 2:
    num = m[0] * pow(2, e) + m[1] * pow(2, e - 1) + m[2] * pow(2, e - 2)
    FPN_numbers.append(num)
    num = -1 * num
    FPN_numbers.append(num)
    m[2] = m[2] + 1
    if m[2] > 1:
        m[1] = m[1] + 1
        m[2] = m[2] - 2
    if m[1] > 1:
        m[0] = m[0] + 1
        m[1] = m[1] - 2
    if m[0] > 1:
        e = e + 1
        m[0] = m[0] - 1

FPN_numbers.append(0.0)

n = np.size(FPN_numbers)
print('enumerate: #F = ', n)
print('corollary: #F = ', pow(2, 3)*(1-(-1)+1)+1)

FPN_numbers.sort()
print('normal FPN numbers: ')
for i in range(n):
    print(FPN_numbers[i], end='\t')
    if i % 5 == 4:
        print()
print()

plt.scatter(FPN_numbers, np.zeros(n), None, 'g', '|')
plt.plot(FPN_numbers, np.zeros(n))
plt.savefig('./pic/problemB_1.png')
plt.show()

FPN_subnormal_numbers = []
e = -1
m = [0, 0, 1]

while e == -1:
    num = m[0] * pow(2, e) + m[1] * pow(2, e - 1) + m[2] * pow(2, e - 2)
    FPN_subnormal_numbers.append(num)
    num = -1 * num
    FPN_subnormal_numbers.append(num)
    m[2] = m[2] + 1
    if m[2] > 1:
        m[1] = m[1] + 1
        m[2] = m[2] - 2
    if m[1] > 1:
        break

m = np.size(FPN_subnormal_numbers)
FPN_subnormal_numbers.sort()
print('subnormal FPN numbers: ')
for i in range(m):
    print(FPN_subnormal_numbers[i], end='\t')
    if i % 5 == 4:
        print()

plt.scatter(FPN_numbers, np.zeros(n), None, 'g', '|')
plt.scatter(FPN_subnormal_numbers, np.zeros(m), None, 'r', '|')
plt.plot(FPN_numbers, np.zeros(n))
plt.savefig('./pic/problemB_2.png')
plt.show()
